import { provide,Context, inject,config } from 'midway';
import {IFilesService,IUserService} from '../interface';
const moment = require('moment');
const Excel = require('exceljs');
// const  xlsx = require('xlsx');
// import { EntityManager } from '../lib/db';
import {getImportXLSXData} from '../utils/helper'
@provide('filesService')
export class FilesService implements IFilesService {
  // constructor(
  //   @inject() private readonly em: EntityManager,
  // ) {
  // }
  @inject()
  ctx: Context;
  @inject('userService')
  service: IUserService;
  @config()
  static;  
  /**
   * 新增
   * @param user 用户实体
   */
// async insertUser(options:IInsertUser):Promise<number | undefined> {
//   return  this.em.db('users').insert(options).returning('id');
// }
async import(options:any){
      const headerMap = {
        用户昵称: 'nickName',
        性别: 'gender',
        头像: 'avatarUrl',
        openid: 'openid',
      };
      try {
    const userData = await getImportXLSXData(options,headerMap)
    return userData
    }catch(error) {
      console.log(error);
      return null
    } 
}
async download() {

  const startDate = moment(new Date).format('YYYY-MM-01');
      // 定义文件信息
      const options = {
        filename: `${this.static.dir}/download/用户账号管理.xlsx`,
        useStyles: true,
        useSharedStrings: true,
      };
   const workbook = new Excel.stream.xlsx.WorkbookWriter(options);
   const worksheet = workbook.addWorksheet(moment(startDate).format('YYYYMM'));
   worksheet.columns = [
    { header: 'id', key: 'id', width: 10 },
    { header: '用户昵称', key: 'nickName', width: 10 },
    { header: '性别', key: 'gender', width: 10 },
    { header: '头像', key: 'avatarUrl', width: 10 },
    { header: 'openid', key: 'openid', width: 10 },
  ];
  worksheet.getRow(1).alignment = { vertical: 'middle', horizontal: 'center' };
  worksheet.getRow(1).height = 50;
  worksheet.getRow(1).font = {
    bold: true,
  };
  worksheet.getRow(1).border = {
    top: { style: 'thin' },
    left: { style: 'thin' },
    bottom: { style: 'thin' },
    right: { style: 'thin' },
  };
  worksheet.getRow(1).commit();
   const users:any = await this.service.fall();
   for (const i of users) {
    const row = {
      id:i.id,
      nickName:i.nickName,
      gender:i.gender,
      avatarUrl:i.avatarUrl,
      openid:i.openid
    }
    const r = worksheet.addRow(row);
    r.border = {
      top: { style: 'thin' },
      left: { style: 'thin' },
      bottom: { style: 'thin' },
      right: { style: 'thin' },
    };
    r.alignment = { vertical: 'middle', horizontal: 'center' };
    // 将数据写入表格
    r.commit();
   }
   worksheet.commit();
   await workbook.commit();
   return true;
}
}
